<template>
    <form-item-wrapper :designer="designer" :field="field" :rules="rules" :design-state="designState"
        :parent-widget="parentWidget" :parent-list="parentList" :index-of-parent-list="indexOfParentList"
        :sub-form-row-index="subFormRowIndex" :sub-form-col-index="subFormColIndex" :sub-form-row-id="subFormRowId">
        <el-input ref="fieldEditor" v-model="polygonDisplayValue" :disabled="field.options.disabled"
            :readonly="field.options.readonly" :size="widgetSize" class="hide-spin-button" :type="inputType"
            :show-password="field.options.showPassword" :placeholder="field.options.placeholder"
            :clearable="field.options.clearable" :minlength="field.options.minLength"
            :maxlength="field.options.maxLength" :show-word-limit="field.options.showWordLimit"
            :prefix-icon="field.options.prefixIcon" :suffix-icon="field.options.suffixIcon" @click="openMap">
            <template #append v-if="field.options.appendButton">
                <el-button :disabled="field.options.disabled || field.options.appendButtonDisabled
                    " @click="emitAppendButtonClick"><svg-icon :icon-class="field.options.buttonIcon" /></el-button>
            </template>
        </el-input>
    </form-item-wrapper>
    <el-dialog v-model="mapVisible" :destroy-on-close="true" title="地图选择">
        <div id="map" style="width: 100%; height: 400px"></div>
    </el-dialog>
</template>

<script>
import FormItemWrapper from "@/components/form-designer/form-widget/field-widget/form-item-wrapper.vue";
import emitter from "@/utils/emitter";
import i18n, { translate } from "@/utils/i18n";
import fieldMixin from "@/components/form-designer/form-widget/field-widget/fieldMixin";
import SvgIcon from "@/components/svg-icon/index";
import mapboxgl from "mapbox-gl";
import "mapbox-gl/dist/mapbox-gl.css";
import MapboxLanguage from "@mapbox/mapbox-gl-language";
import { nextTick, ref } from "vue";
export default {
    name: "mapPolygon-widget",
    componentName: "FieldWidget", //必须固定为FieldWidget，用于接收父级组件的broadcast事件
    mixins: [emitter, fieldMixin, i18n],
    data() {
        return {
            map: null,
            mapVisible: false,
            oldFieldValue: null, //field组件change之前的值
            fieldModel: [],
            rules: [],
        };
    },
    props: {
        field: Object,
        parentWidget: Object,
        parentList: Array,
        indexOfParentList: Number,
        designer: Object,

        designState: {
            type: Boolean,
            default: false,
        },

        subFormRowIndex: {
        /* 子表单组件行索引，从0开始计数 */ type: Number,
            default: -1,
        },
        subFormColIndex: {
        /* 子表单组件列索引，从0开始计数 */ type: Number,
            default: -1,
        },
        subFormRowId: {
        /* 子表单组件行Id，唯一id且不可变 */ type: String,
            default: "",
        },
    },
    components: {
        FormItemWrapper,
        SvgIcon,
    },
    created() {
        /* 注意：子组件mounted在父组件created之后、父组件mounted之前触发，故子组件mounted需要用到的prop
             需要在父组件created中初始化！！ */
        this.initFieldModel();
        this.registerToRefList();
        this.initEventHandler();
        this.buildFieldRules();

        this.handleOnCreated();
    },

    mounted() {
        this.handleOnMounted();
    },

    beforeUnmount() {
        this.unregisterFromRefList();
    },
    methods: {
        handleCloseCustomEvent() {
            if (!!this.field.options.onClose) {
                let changeFn = new Function(this.field.options.onClose);
                changeFn.call(this);
            }
        },
        openMap() {
            if (this.designState) return;
            this.mapVisible = true;
            nextTick(() => {
                this.initMap();
            });
        },
        inputType() {
            if (this.field.options.type === "number") {
                return "text"; //当input的type设置为number时，如果输入非数字字符，则v-model拿到的值为空字符串，无法实现输入校验！故屏蔽之！！
            }

            return this.field.options.type;
        },
        initMap() {
            // Mapbox初始化
            mapboxgl.accessToken =
                "pk.eyJ1Ijoid29kZjU5MDMzIiwiYSI6ImNtMWk0YTg1MDBpNjkyanNlZDUwZ3ljODYifQ.zJxfW-O84OOmKgzrCB8ZIg"; // 替换为你的Mapbox访问令牌
            this.map = new mapboxgl.Map({
                container: "map", // 容器ID
                style: this.field.options.mapsrc || "mapbox://styles/mapbox/streets-v11", // 地图样式
                center: [114.26, 30.58], // 默认坐标
                zoom: 12, // 默认缩放等级
            });
            this.map.addControl(new MapboxLanguage({ defaultLanguage: "zh-Hans" }));
            this.map.on('load', (e) => {
                this.map.getCanvas().style.cursor = "crosshair";
                if (Array.isArray(this.fieldModel) && this.fieldModel.length > 0) {
                    this.map.addSource('polygon', {
                        type: 'geojson',
                        data: {
                            type: 'Feature',
                            geometry: {
                                type: 'Polygon',
                                coordinates: [this.fieldModel],
                            },
                        },
                    });
                    // 添加多边形的样式
                    this.map.addLayer({
                        id: 'polygon',
                        type: 'fill',
                        source: 'polygon',
                        layout: {},
                        paint: {
                            'fill-color': 'pink', // 填充颜色
                            'fill-opacity': 0.5,  // 填充透明度
                        },
                    });
                }
                this.map.on("click", (e) => {
                    // 添加点击位置的经纬度到多边形坐标数组
                    this.fieldModel.push([e.lngLat.lng, e.lngLat.lat]);

                    // 如果多边形有三个或更多点，则更新多边形
                    if (this.fieldModel.length > 2) {
                        this.map.getSource('polygon').setData({
                            type: 'Feature',
                            geometry: {
                                type: 'Polygon',
                                coordinates: [this.fieldModel],
                            },
                        });
                    } else {
                        // 首次点击时添加数据源
                        this.map.addSource('polygon', {
                            type: 'geojson',
                            data: {
                                type: 'Feature',
                                geometry: {
                                    type: 'Polygon',
                                    coordinates: [this.fieldModel],
                                },
                            },
                        });

                        // 添加多边形的样式
                        this.map.addLayer({
                            id: 'polygon',
                            type: 'fill',
                            source: 'polygon',
                            layout: {},
                            paint: {
                                'fill-color': 'pink', // 填充颜色
                                'fill-opacity': 0.5,  // 填充透明度
                            },
                        });
                    }
                });
                //双击关闭地图选择框
                this.map.on("dblclick", () => {
                    this.mapVisible = false;
                    this.handleChangeEvent(this.fieldModel)
                });
                this.fieldModel = []; 
                this.map.on("mousemove", (e) => {
                    if (this.fieldModel.length > 0) {
                        // 更新线段到鼠标位置
                        const newCoordinates = [...this.fieldModel, [e.lngLat.lng, e.lngLat.lat]];
                        this.map.getSource('polygon').setData({
                            type: 'Feature',
                            geometry: {
                                type: 'Polygon',
                                coordinates: [newCoordinates],
                            },
                        });

                    }
                });
            })
        },
    },
    computed: {
        polygonDisplayValue() {
            return Array.isArray(this.fieldModel) &&this.fieldModel?.length > 0 ? '已绘制' : '';
        }
    }
};
</script>

<style lang="scss" scoped>
@import "../../../styles/global.scss";
/* form-item-wrapper已引入，还需要重复引入吗？ */
</style>